package itsm.isperp.framework.core.context;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.WebApplicationContext;

/**
 * 一个用来加载框架properties配置的文件类，<br>
 * 该类会自动扫描classpath下所有default类型以及用户自定义的的properties文件，并将其加载<br>
 * 用户自定义的的properties配置文件会覆盖default类型的properties文件内容
 * 
 */
public class PropertiesConfigurationLoader extends
		PropertyPlaceholderConfigurer implements ApplicationContextAware {

	private String frameworkPropertiesFile = "config.properties";

	/**
	 * 覆盖父类方法，用来加载所有framework的properties文件<br>
	 * 首先加载位于classpath当中所有的default类型的framework的properties文件,<br>
	 * 然后再加载位于classpath根下的framework的properties文件
	 * */
	@Override
	protected void loadProperties(Properties properties) throws IOException {
		super.loadProperties(properties);
		File f = new File(this.frameworkPropertiesFile);
		if (f.exists()) {
			Properties p = new Properties();
			FileInputStream fin = new FileInputStream(f);
			p.load(fin);
			CollectionUtils.mergePropertiesIntoMap(p, properties);
			fin.close();
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		WebApplicationContext context = ((WebApplicationContext) applicationContext);
		frameworkPropertiesFile = context.getServletContext().getRealPath(
				frameworkPropertiesFile);
	}
}
